<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文章评论</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }

        h1 {
            text-align: center;
        }

        .comment-container {
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
            margin: 20px auto;
            width: 80vw;
        }

        .comment {
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 10px;
            margin-bottom: 10px;
            width: 48%;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
            transition: box-shadow 0.3s ease;
        }

        .comment:hover {
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        .comment-author {
            font-weight: bold;
            margin-bottom: 5px;
        }

        .comment-date {
            color: #777;
            font-size: 12px;
            margin-bottom: 5px;
        }

        .comment-content {
            line-height: 1.4;
            max-height: 150px;
            overflow-y: auto;
            word-wrap: break-word;
            margin-bottom: 10px;
        }

        /* .search-bar {
            margin: 20px;
            text-align: center;
        }

        .search-bar input {
            padding: 10px;
            font-size: 16px;
            margin-right: 10px;
            border: 1px solid #ccc;
            border-radius: 3px;
        }

        .search-bar button {
            padding: 10px 20px;
            background-color: #007BFF;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        .search-bar button:hover {
            background-color: #0056b3;
        } */

        .pagination {
            text-align: center;
            margin: 20px auto;
            width: 80vh;
        }

        .pagination button {
            padding: 10px 15px;
            margin: 0 5px;
            background-color: #007BFF;
            border: 1px solid #ccc;
            color: #fff;
            border-radius: 3px;
            cursor: pointer;
            transition: background-color 0.3s ease, border-color 0.3s ease;
        }
        .back{
            float: right;
        }
    </style>
</head>

<body>
<!-- <div class="search-bar">
    <input type="text" id="searchInput" placeholder="请输入作者关键词进行搜索">
    <button onclick="searchComments()">搜索</button>
</div> -->

<div class="comment-container" id="commentContainer"></div>
<div class="pagination">
    <button onclick="prevPage()" id="prevButton">上一页</button>
    <span id="currentPage">1</span> / <span id="totalPages">1</span>
    <button onclick="nextPage()" id="nextButton">下一页</button>
    <button class="back"onclick=" window.location.href = '/admin/home'" >返回</button>
</div>



<script>
    // 模拟评论数据，实际应用中需要从后端获取
    let comments = []
    // 获取当前 URL 的查询参数
    const urlParams = new URLSearchParams(window.location.search);
    const articleId = parseInt(urlParams.get('id'));

    const commentContainer = document.getElementById('commentContainer');
    // const searchInput = document.getElementById('searchInput');
    const currentPageElement = document.getElementById('currentPage');
    const totalPagesElement = document.getElementById('totalPages');
    const prevButton = document.getElementById('prevButton');
    const nextButton = document.getElementById('nextButton');

    let currentPage = 1;
    let pageSize = 8; // 每页展示8条评论
    let filteredComments = comments;
    let  totalPages = 0;


    const getdata  = ()=>{
        fetch(`/comment/byArticleId/${articleId}?pageNow=${currentPage}&pageSize=${pageSize}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.code === 0) {
                    comments = data.data;
                    filteredComments = comments;
                    // 从第一条评论中提取 totalPages（假设所有评论对象均包含该字段）
                    totalPages = data.data[0]?.totalPages || 1;
                    console.log('查询成功，评论数据：', data.data);
                    updatePagination();
                } else {
                    console.error('查询失败：', data.message);
                }
            })
            .catch(error => {
                console.error('There has been a problem with your fetch operation:', error);
            });
    }
    getdata();


    function renderComments(commentsToRender) {
        commentContainer.innerHTML = '';
        if (commentsToRender.length === 0) {
            const noCommentElement = document.createElement('p');
            noCommentElement.textContent = '暂无评论';
            commentContainer.appendChild(noCommentElement);
        } else {
            commentsToRender.forEach(comment => {
                const commentDiv = document.createElement('div');
                commentDiv.classList.add('comment');

                const authorElement = document.createElement('p');
                authorElement.classList.add('comment-author');
                authorElement.textContent = `用户名: ${comment.user.username}`;

                const dateElement = document.createElement('p');
                dateElement.classList.add('comment-date');
                dateElement.textContent = `日期: ${comment.comment.createTime}`;

                const contentElement = document.createElement('p');
                contentElement.classList.add('comment-content');
                contentElement.textContent = comment.comment.content;

                const deleteButton = document.createElement('button');
                deleteButton.textContent = '删除';
                deleteButton.style.backgroundColor = '#dc3545';
                deleteButton.style.color = 'white';
                deleteButton.style.border = 'none';
                deleteButton.style.padding = '8px 15px';
                deleteButton.style.borderRadius = '3px';
                deleteButton.style.cursor = 'pointer';
                deleteButton.style.transition = 'background-color 0.3s ease';
                deleteButton.onclick = function () {
                    const commentId = comment.comment.commentId;
                    const deleteUrl = `/comment/${commentId}`;
                    fetch(deleteUrl, {
                        method: 'DELETE',
                        credentials: 'include' // 确保发送请求时带上Cookie

                    })
                        .then(response => {
                            if (response.ok) {
                                return response.json();
                            }
                            throw new Error('删除请求失败');
                        })
                        .then(data => {
                            if (data.code === 0) {
                                alert('评论删除成功')
                                currentPage = 1;
                                getdata(); // 重新获取数据并更新页面显示
                            }
                            else{
                                alert('评论删除失败')
                                console.log('删除失败', data.message);
                            }

                        })
                        .catch(error => {
                            console.error('删除评论时出错:', error);
                        });
                };
                deleteButton.addEventListener('mouseover', function () {
                    this.style.backgroundColor = '#c82333';
                });
                deleteButton.addEventListener('mouseout', function () {
                    this.style.backgroundColor = '#dc3545';
                });

                commentDiv.appendChild(authorElement);
                commentDiv.appendChild(dateElement);
                commentDiv.appendChild(contentElement);
                commentDiv.appendChild(deleteButton);

                commentContainer.appendChild(commentDiv);
            });
        }
    }

    // function searchComments() {
    //     const keyword = searchInput.value.toLowerCase();
    //     // 使用更新后的 comments 数组进行过滤
    //     filteredComments = comments.filter(comment => comment.author.toLowerCase().includes(keyword));
    //     currentPage = 1; // 重置到第一页
    //     updatePagination();
    // }

    // searchInput.addEventListener('keydown', function (event) {
    //     if (event.key === 'Enter') {
    //         searchComments();
    //     }
    // });

    function updatePagination() {
        // const total = filteredComments.length;
        // const totalPages = Math.ceil(total / pageSize);
        currentPageElement.textContent = currentPage;
        totalPagesElement.textContent = totalPages;
        // 禁用/启用分页按钮
        prevButton.disabled = currentPage <= 1;
        nextButton.disabled = currentPage >= totalPages;
        renderComments(filteredComments);

        if (currentPage === 1) {
            prevButton.disabled = true;
        } else {
            prevButton.disabled = false;
        }

        if (currentPage === totalPages) {
            nextButton.disabled = true;
        } else {
            nextButton.disabled = false;
        }
    }

    function prevPage() {
        if (currentPage > 1) {
            currentPage--;
            getdata()
            updatePagination();
        }
    }

    function nextPage() {
        // const totalPages = Math.ceil(filteredComments.length / pageSize);
        if (currentPage < totalPages) {
            currentPage++;
            getdata()
            updatePagination();
        }
    }
    updatePagination();
</script>
</body>

</html>